from flask import Flask, request, jsonify, send_file
import os
import time
import requests
from datetime import datetime
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 启用跨域支持

# 日志文件配置
LOG_DIR = 'tracker_logs'
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)
LOG_FILE = os.path.join(LOG_DIR, 'tracker_startup.log')

# PT服务器配置
PT_SERVER_URL = ""


def log_to_file(message):
    """将消息写入日志文件"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(LOG_FILE, 'a', encoding='utf-8') as f:
        f.write(f"[{timestamp}] {message}\n")


def notify_pt_server(tracker_name, ip, port, is_public):
    """通知PT服务器Tracker已连接"""
    try:
        # PT服务器API端点
        endpoint = f"{PT_SERVER_URL}/api/network/tracker/connect"

        # 准备请求数据
        data = {
            "trackerName": tracker_name,
            "trackerIp": ip,
            "trackerPort": port,
            "isPublic": is_public
        }

        # 记录发送请求信息
        log_to_file(f"正在通知PT服务器: 发送请求到 {endpoint}, 数据: {data}")

        # 发送POST请求
        response = requests.post(endpoint, json=data, timeout=10)

        # 解析响应
        result = response.json()

        if response.status_code == 200:
            api_code = result.get('code', 0)
            message = result.get('message', '')

            if api_code == 200:  # API成功且验证通过
                log_to_file(f"PT服务器通知成功: {message}")
                return True, result
            else:  # API成功但验证失败
                log_to_file(f"PT服务器验证失败: {message}")
                return False, result
        else:
            log_to_file(f"PT服务器通知失败: HTTP {response.status_code} - {response.text}")
            return False, response.text

    except Exception as e:
        error_message = f"PT服务器通知异常: {str(e)}"
        log_to_file(error_message)
        return False, error_message


@app.route('/api/tracker/startup', methods=['POST'])
def record_startup():
    """记录tracker启动信息并通知PT服务器"""
    try:
        data = request.json

        # 获取必要信息
        tracker_name = data.get('tracker_name', 'unknown-tracker')
        reported_ip = data.get('ip', request.remote_addr)  # 优先使用上报的IP，否则使用请求IP
        port = data.get('port', 0)
        is_public = data.get('is_public', False)  # 获取是否为公网Tracker

        # 获取请求发来时的信息
        request_ip = request.remote_addr
        request_port = request.environ.get('REMOTE_PORT', 'unknown')

        # 构建详细的日志消息
        log_message = (f"Tracker '{tracker_name}' 启动 - "
                       f"Tracker声明: IP={reported_ip or '未提供'}, Port={port}, IsPublic={is_public}, "
                       f"请求来源: IP={request_ip}, Port={request_port}")

        # 写入日志文件
        log_to_file(log_message)

        # 通知PT服务器
        success, result = notify_pt_server(tracker_name, reported_ip, port, is_public)

        # 返回响应
        response = {
            'success': True,
            'timestamp': time.time(),
            'message': 'Startup information recorded',
            'tracker_info': {
                'name': tracker_name,
                'ip': reported_ip,
                'port': port,
                'is_public': is_public
            },
            'pt_server_notification': {
                'success': success,
                'result': result
            }
        }

        return jsonify(response)
    except Exception as e:
        error_message = f"处理请求时发生错误: {str(e)}"
        log_to_file(error_message)
        return jsonify({
            'success': False,
            'message': error_message
        }), 500


@app.route('/api/logs', methods=['GET'])
def get_logs():
    """下载日志文件"""
    if not os.path.exists(LOG_FILE):
        return jsonify({
            'error': 'Log file does not exist'
        }), 404

    return send_file(LOG_FILE,
                     mimetype='text/plain',
                     as_attachment=True,
                     download_name='tracker_startup.log')


@app.route('/api/logs/view', methods=['GET'])
def view_logs():
    """查看最近的日志（不下载）"""
    if not os.path.exists(LOG_FILE):
        return jsonify({
            'error': 'Log file does not exist'
        }), 404

    # 获取参数，默认显示最后50行
    lines = request.args.get('lines', default=50, type=int)

    with open(LOG_FILE, 'r', encoding='utf-8') as f:
        all_lines = f.readlines()
        last_lines = all_lines[-lines:] if lines < len(all_lines) else all_lines

    return jsonify({
        'total_lines': len(all_lines),
        'showing_lines': len(last_lines),
        'logs': last_lines
    })


@app.route('/status', methods=['GET'])
def status():
    """服务器状态检查"""

    # 检查日志文件大小
    log_size = 0
    log_count = 0
    if os.path.exists(LOG_FILE):
        log_size = os.path.getsize(LOG_FILE)
        with open(LOG_FILE, 'r', encoding='utf-8') as f:
            log_count = len(f.readlines())

    uptime_seconds = time.time() - start_time
    days, remainder = divmod(uptime_seconds, 86400)
    hours, remainder = divmod(remainder, 3600)
    minutes, seconds = divmod(remainder, 60)

    uptime_str = ""
    if days > 0:
        uptime_str += f"{int(days)}天 "
    if hours > 0 or days > 0:
        uptime_str += f"{int(hours)}小时 "
    if minutes > 0 or hours > 0 or days > 0:
        uptime_str += f"{int(minutes)}分钟 "
    uptime_str += f"{int(seconds)}秒"

    return jsonify({
        'status': 'running',
        'uptime': uptime_str,
        'uptime_seconds': uptime_seconds,
        'pt_server': PT_SERVER_URL,
        'started_at': datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S'),
        'log_file': LOG_FILE,
        'log_size': f"{log_size / 1024:.2f} KB",
        'log_entries': log_count
    })


@app.route('/', methods=['GET'])
def home():
    """首页"""
    return jsonify({
        'service': 'Tracker Startup Logging Service',
        'status': 'running',
        'endpoints': {
            '/api/tracker/startup': 'POST - 记录tracker启动信息',
            '/api/logs': 'GET - 下载日志文件',
            '/api/logs/view': 'GET - 查看最近日志',
            '/status': 'GET - 查看服务状态'
        }
    })


# 服务器启动时间
start_time = time.time()

if __name__ == '__main__':
    # 记录本服务启动信息
    log_to_file(f"Tracker startup logging service started - PT服务器地址: {PT_SERVER_URL}")
    print(f"Server running at http://0.0.0.0:5111/")
    app.run(host='0.0.0.0', port=5111, debug=False)